<template>
  <div class="app-container">
    <el-form :model="recordInfo" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="店铺名称" required>
            <el-input
              v-model="recordInfo.storeName"
              class="input-width"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="店铺联系人" required>
            <el-input
              v-model="recordInfo.userName"
              class="input-width"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" required>
            <el-input
              v-model="recordInfo.mobile"
              class="input-width"
              @input="queryMobile"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="店铺地址" required>
        <el-row>
          <el-col :span="4">
            <el-cascader
              ref="refHandle"
              v-model="addressValue"
              style="width: 100%;"
              :props="areaprop"
              clearable
            />
          </el-col>
          <el-col :span="4" style="margin-left: 4px">
            <el-form-item prop="areaId">
              <el-input v-model="recordInfo.address" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="店铺店型">
        <el-row>
          <el-col :span="4" style="margin-left: 4px">
            <el-form-item prop="storeTypeBusinessCircleId">
              <el-select
                v-model="recordInfo.storeTypeBusinessCircleId"
              >
                <el-option
                  v-for="(item, index) in storeTypeBusinessCircleList"
                  :key="index"
                  :label="item.fieldName"
                  :value="item.fieldId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="margin-left: 4px">
            <el-form-item prop="storeTypeStoreAreaId">
              <el-select
                v-model="recordInfo.storeTypeStoreAreaId"
              >
                <el-option
                  v-for="(item, index) in storeTypeStoreAreaList"
                  :key="index"
                  :label="item.fieldName"
                  :value="item.fieldId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="房租到期日期">
            <el-date-picker v-model="recordInfo.receivingAccount" type="date" placeholder="选择日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租约到期是否能续签">
            <el-select v-model="recordInfo.leaseExpirationCanRenewed">
              <el-option label="请选择" value="0" />
              <el-option label="能" value="1" />
              <el-option label="不能" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="租金">
            <el-input
              v-model="recordInfo.openingBank"
              :disabled="action === 'info'"
              class="input-width"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租金支付方式">
            <el-select v-model="recordInfo.rentPayMethod">
              <el-option label="请选择" value="0" />
              <el-option label="押三付" value="1" />
              <el-option label="押一付一" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="营业执照">
            <el-input
              v-model="recordInfo.businessLicense"
              class="input-width"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" />
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人">
            <el-select v-model="recordInfo.attributeUserId" :disabled="action === 'info'">
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button
      type="warning"
      class="save-btn"
      @click="save"
    >保存
    </el-button>
    <div v-if="repeatOrganizationList.length > 0" class="repeat-organization-view">
      <div v-if="repeatOrganizationList.length > 0" class="repeat-organization-content">
        <div class="title">此手机号已存在以下店铺，请确认是否重复</div>
        <div v-for="(item,index) in repeatOrganizationList" :key="index" class="item">
          <div class="name">{{ item.storeName }}</div>
          <div class="address">{{ item.address }}</div>
        </div>
        <div class="button-view">
          <el-button
            class="button"
            @click="addByRepeatOrganization"
          >继续添加
          </el-button>
          <el-button
            class="button"
            type="success"
            @click="cancelByRepeatOrganization"
          >取消
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/api/index'
import locationMixin from '@/mixins/modules/location'
import iframeMessageMixin from '@/mixins/modules/iframeMessage'
import { mapGetters } from 'vuex'
import filters from '@/filters/index'

export default {
  components: {},
  filters: { ...filters },
  mixins: [locationMixin, iframeMessageMixin],
  data() {
    return {
      repeatOrganizationList: [],
      addressValue: [],
      organizationHeadList: [],
      userList: [],
      tabActiveName: 'basicInfo',
      storeTypeBusinessCircleList: [],
      storeTypeStoreAreaList: [],
      recordInfo: {
        storeName: '',
        contactName: '',
        mobile: '',
        geoAreaId: '',
        address: '',
        businessLicense: '',
        storeTypeBusinessCircleId: '',
        storeTypeStoreAreaId: '',
        organizationState: 1
      },
      areaprop: {
        lazy: true,
        lazyLoad(node, resolve) {
          setTimeout(() => {
            if (node.level === 0) {
              var arr = []
              api.getLocationList({ parentId: 0, page: 1, pageSize: 999 }).then(response => {
                for (let i = 0; i < response.list.length; i++) {
                  if (response.list[i].lastLevel === true) {
                    arr.push(
                      {
                        value: response.list[i].geoAreaId,
                        label: response.list[i].areaName,
                        leaf: true
                      }
                    )
                  } else {
                    arr.push(
                      {
                        value: response.list[i].geoAreaId,
                        label: response.list[i].areaName,
                        leaf: false
                      }
                    )
                  }
                }
                resolve(arr)
              })
            }
            if (node.level === 1) {
              // eslint-disable-next-line no-redeclare
              var arr = []
              api.getLocationList({ parentId: node.value, page: 1, pageSize: 999 }).then(response => {
                for (let i = 0; i < response.list.length; i++) {
                  if (response.list[i].lastLevel === true) {
                    arr.push(
                      {
                        value: response.list[i].geoAreaId,
                        label: response.list[i].areaName,
                        leaf: true
                      }
                    )
                  } else {
                    arr.push(
                      {
                        value: response.list[i].geoAreaId,
                        label: response.list[i].areaName,
                        leaf: false
                      }
                    )
                  }
                }
                resolve(arr)
              })
            } else if (node.level === 2) {
              // eslint-disable-next-line no-redeclare
              var arr = []
              api.getLocationList({ parentId: node.value, page: 1, pageSize: 999 }).then(response => {
                for (let i = 0; i < response.list.length; i++) {
                  if (response.list[i].lastLevel === true) {
                    arr.push(
                      {
                        value: response.list[i].geoAreaId,
                        label: response.list[i].areaName,
                        leaf: true
                      }
                    )
                  } else {
                    arr.push(
                      {
                        value: response.list[i].geoAreaId,
                        label: response.list[i].areaName,
                        leaf: false
                      }
                    )
                  }
                }
                resolve(arr)
              })
            }
          }, 100)
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  created() {
    const query = this.$route.query
    if (query.params) {
      const params = JSON.parse(decodeURIComponent(this.$Base64.decode(query.params)))
      this.recordInfo = { ...this.recordInfo, ...params }
      this.action = params.action
      if (this.recordInfo.potentialCustomerStoreId) {
        this.getData()
      }
      this.getUserList()
    }
    this.recordInfo.attributeUserId = this.$store.getters.userInfo.userId
    this.getLocationList(0, 'provinceList')
    this.getStoreTypeBusinessCircleList()
    this.getStoreTypeStoreAreaList()
  },
  methods: {
    getUserList() {
      this.$api.getUserList({ returnCount: true, page: 1, pageSize: 999 }).then(res => {
        this.userList = res.list
      })
    },
    async getData() {
      let loading
      try {
        loading = this.$loading({
          lock: true,
          text: '请稍等...'
        })
        this.recordInfo = await this.$api.getPotentialCustomerStoreDetail({ potentialCustomerStoreId: this.recordInfo.potentialCustomerStoreId })
        if (Number(this.recordInfo.storeTypeBusinessCircleId) === 0) {
          this.recordInfo.storeTypeBusinessCircleId = ''
        }
        if (Number(this.recordInfo.storeTypeStoreAreaId) === 0) {
          this.recordInfo.storeTypeStoreAreaId = ''
        }
        this.addressValue = this.recordInfo.geoAreaIdList
      } catch (err) {
        console.error(err)
      } finally {
        loading && loading.close()
      }
    },
    queryMobile() {
      if (this.recordInfo.mobile.length > 11) {
        this.recordInfo.mobile = this.recordInfo.mobile.substring(0, 11)
      } else if (this.recordInfo.mobile.length === 11) {
        this.$api.getOrganizationList({
          organizationType: this.recordInfo.organizationType === '' ? 5 : this.recordInfo.organizationType,
          adminUserMobile: this.recordInfo.mobile,
          returnCount: false,
          pageSize: 1
        }).then(res => {
          if (res.list.length === 1) {
            this.repeatOrganizationList = res.list
          }
        })
      }
    },
    cancelByRepeatOrganization() {
      this.repeatOrganizationList = []
      this.recordInfo.mobile = ''
    },
    addByRepeatOrganization() {
      this.repeatOrganizationList = []
    },
    async save() {
      let loading
      try {
        if (!this.recordInfo.storeName) {
          return this.$message({ type: 'warning', message: '请填写店铺名称' })
        }
        if (!this.recordInfo.mobile) {
          return this.$message({ type: 'warning', message: '请填写手机号' })
        }
        if (this.addressValue.length === 3) {
          this.recordInfo.geoAreaId = this.addressValue[2]
        } else if (this.addressValue.length === 2) {
          this.recordInfo.geoAreaId = this.addressValue[1]
        }
        if (!this.recordInfo.geoAreaId) {
          return this.$message({ type: 'warning', message: '请选择地区' })
        }
        if (!this.recordInfo.address) {
          return this.$message({ type: 'warning', message: '请填写详细地址' })
        }
        loading = this.$loading({
          lock: true,
          text: '请稍等...'
        })
        const params = { ...this.recordInfo }
        if (!this.recordInfo.organizationId) {
          const addRecordInfoResult = await this.$api.addOrganizationInfo(params)
          this.recordInfo.organizationId = addRecordInfoResult.id
          this.$message({ type: 'success', message: '创建成功' })
        } else {
          await this.$api.editOrganizationInfo(params)
          this.$message({ type: 'success', message: '保存成功' })
          this.recordInfo = {
            storeName: '',
            contactName: '',
            mobile: '',
            geoAreaId: '',
            address: '',
            businessLicense: '',
            storeTypeBusinessCircleId: '',
            storeTypeStoreAreaId: '',
            organizationState: 1
          }
        }
        this.sendCloseTabMessage()
      } catch (err) {
        console.error(err)
      } finally {
        loading && loading.close()
      }
    },
    getStoreTypeBusinessCircleList() {
      api.getCommonFieldList(
        {
          commonFieldCategoryIdList: [3],
          page: 1,
          pageSize: 999,
          returnCount: true
        }
      ).then(res => {
        this.storeTypeBusinessCircleList = res.list
      })
    },
    getStoreTypeStoreAreaList() {
      api.getCommonFieldList(
        {
          commonFieldCategoryIdList: [4],
          page: 1,
          pageSize: 999,
          returnCount: true
        }
      ).then(res => {
        this.storeTypeStoreAreaList = res.list
      })
    },
    editClick(item) {
      this.$addTab('basicArchivesStaffEdit', { action: 'edit', userId: this.recordInfo.adminUserId })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .input-width {
    width: 300px;
  }

  .img-upload-container {
    width: 150px;
    height: 213px;
    padding: 6px;
    text-align: center;
    border: 1px solid #ececec;
    position: relative;
    margin: 0 10px 10px 0;

    .el-button {
      width: 140px;
    }

    .delete-ico {
      position: absolute;
      right: 4px;
      top: 4px;
      color: red;
      display: none;
    }

    ::v-deep .action-label {
      .el-icon-delete {
        display: none;
      }
    }
  }

  .img-upload-container:hover {
    .delete-ico {
      display: inline;
    }
  }

  .img-upload-add-container {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    color: #666666;
  }

  .save-btn {
    position: absolute;
    top: 10px;
    right: 10px;
  }

  .repeat-organization-view {
    z-index: 1000;
    position: fixed;
    display: flex;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, .3);

    .repeat-organization-content {
      width: 35%;
      box-shadow: 0 0 10px 0px #000;
      background-color: #fff;
      padding: 10px;
      border-radius: 10px;

      .title {
        color: #f00;
        font-size: 18px;
        font-weight: bold;
        height: 60px;
        line-height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .item {
        padding: 10px;
        border-bottom: 1px #eee dotted;

        .name {
          font-size: 16px;
          font-weight: bold;
        }

        .address {
          color: #aaa;
          margin-top: 10px;
        }
      }

      .button-view {
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;

        .button {
          width: 120px;
          margin-left: 10px;
          margin-right: 10px;
        }
      }
    }
  }
}
</style>
